package util;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.http.HttpServletResponse;

import snsdbook.engine.AbortError;
import snsdbook.engine.message.MessageInterface;
import view.ClientGUI;

public abstract class Util {

  public static String[] toArray(ArrayList<String> arg) {
    String[] ret = new String[arg.size()];
    arg.toArray(ret);
    return ret;
  }
  
  public static int[] toArrayInt(String[] obj) {
    int[] ret = new int[obj.length];
    for (int i = 0; i < ret.length; ++i) {
      ret[i] = Integer.valueOf(obj[i]);
    }
    return ret;
  }
  
  public static void PrintAndClose(HttpServletResponse response,
                                   String message) throws IOException {
    PrintWriter writer = response.getWriter();
    writer.print(message);
    writer.close();
  }
  
  private static ClientGUI gui_ = null;
  public static void RegisterGUI(ClientGUI gui) {
    gui_ = gui;
  }
  
  public static void Log(String text) {
    System.out.println(text);
    if (gui_ != null) gui_.AddLog(text);
  }
  
  public static void Fatal(String text) {
    System.err.println("FATAL: " + text);
    throw new Error(text);
  }
  
  public static void Fatal(Exception ex) {
    System.err.println("FATAL: " + ex.toString());
    throw new Error(ex.toString());
  }
  
  public static void Warning(String text) {
    System.err.println("WARNING: " + text);
    if (gui_ != null) gui_.AddLog("WARNING: " + text);
  }

  public static void Warning(Exception ex) {
    System.err.println("WARNING: " + ex.toString());
    if (gui_ != null) gui_.AddLog("WARNING: " + ex.toString());
  }
  
  public static void Send(ObjectOutputStream os, MessageInterface message) {
    Util.Log("Sending " + message.toString());
    try {
      os.writeObject(message);
    } catch (IOException e) {
      Util.Warning(e);
      throw new AbortError();
    }
  }
  
  public static MessageInterface Receive(ObjectInputStream is) {
    try {
      MessageInterface reply = (MessageInterface)is.readObject();
      Util.Log("Received message:" + reply.toString());
      return reply;
    } catch (IOException e) {
      Util.Warning(e);
      throw new AbortError();
    } catch (ClassNotFoundException e) {
      Util.Fatal(e);
    }
    return null;
  }
  
}
